#include<iostream>
#include<memory>
#include<vector>
#include<cstdio>

#include"udpserver.hpp"

//服务器使用说明
void Usage(const std::string& proc)
{
    std::cout << "\n\rUsage: " << proc << " port[1024]+\n" << std::endl;
}


//服务器处理数据的方式
std::string Handle(const std::string& str,const std::string& ip,const uint16_t& port)
{
    std::cout << "[" << ip << ":" << port << "]" << "#" << str <<std::endl;
    std::string res;
    res += "server get a message:";
    res += str;
    std::cout << res << std::endl;

    return res;
}


//检查函数
bool SafeCheck(const std::string& cmd)
{
    std::vector<std::string> badCmd = 
    {
        "rm",
        "while",
        "mkdir",
        "touch",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top"
    };

    //查询不被允许的命令
    for(auto& s : badCmd)
    {
        int pos = cmd.find(s);
        if(pos != std::string::npos) return false;
    }

    return true;

}


//执行命令并且返回结果的回调函数
std::string ExcuteCommand(const std::string& cmd)\
{
    std::cout << "get a command: " << cmd << std::endl;
    if(SafeCheck(cmd) == false)
    {
        return "Disallowed orders";
    }

    //调用popen执行命令
    FILE* fp = popen(cmd.c_str(),"r");
    if(fp == nullptr)
    {
        return "popen error!!";
    }

    char buffer[128];
    while(true)
    {
        ssize_t n = fread(buffer,sizeof(buffer),1,fp);
        if(n == 0) break;
    }

    std::string ret(buffer);
    pclose(fp);

    return ret;
}



int main(int argc,char* argv[])
{
    //传入参数不是2个就报错
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    //提取字符串为服务端端口号
    uint16_t port = std::stoi(argv[1]);

    //服务器默认0.0.0.0可以接收多个ip信息，如果只设置为一个固定ip，服务器其它ip信息就接收不到
    std::unique_ptr<udpserver> usvr(new udpserver(port));

    usvr->Init();
    usvr->Start(Handle);

    return 0;
}